﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace olierFrm.Web
{
    public class SmartINI
    {
        public static Dictionary<string, Dictionary<string, string>> LoadIni(string iniString)
        {
            Dictionary<string, Dictionary<string, string>> iniObject = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
            if (iniString == null || iniString.Replace("\r", "").Replace("\n", "").Trim().Length == 0)
            {
                return iniObject;
            }
            byte[] bSource = Encoding.UTF8.GetBytes(iniString);
            MemoryStream stream = new MemoryStream(bSource);
            StreamReader streamread = new StreamReader(stream);
            string section = "";
            while (streamread.Peek() != -1)
            {
                string str = streamread.ReadLine().Trim();
                if (str.Length > 0 && !(str.Substring(0, 1) == ";"))
                {
                    if (str.Substring(0, 1) == "[")
                    {
                        section = str.Substring(1, str.IndexOf("]") - 1);
                        iniObject.Add(section, new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
                    }
                    if (str.IndexOf("=") > 0)
                    {
                        try
                        {
                            iniObject[section].Add(str.Substring(0, str.IndexOf("=")), str.Substring(str.IndexOf("=") + 1));
                        }
                        catch
                        {
                            iniObject[section].Add(str.Substring(0, str.IndexOf("=")), "");
                        }
                    }
                }
            }
            stream.Close();
            return iniObject;
        }
    }
}
